package homework_4_minesweeper;

import java.util.HashSet;
import java.util.Random;

public class MineMap {

    private static HashSet<Integer> mineMap=new HashSet<>();
    public static void setMineMap(int row,int col,int num,int position){        //生成雷区需要调用的方法
        int posRow=MinesweeperUtilities.returnToRow(position,col);
        int posCol=MinesweeperUtilities.returnToCol(position,col);
        HashSet<Integer> safeCells=new HashSet<>();
        safeCells.add(position);
        for(int c=posCol-1;c<=posCol+1;c++){
            for (int r=posRow-1;r<=posRow+1;r++){
                if(MinesweeperUtilities.isValid(r,c,row,col)){
                    safeCells.add(MinesweeperUtilities.codeToNum(r,c,col));
                }
            }
        }
        //上面的第一个add和后面的for是排除用户点击的格子以及它3x3范围内的格子，防止开局就踩到雷等烦人的情况
        generateMines(row,col,num,safeCells);
    }

    public static boolean isMine(int position) {
        return mineMap.contains(position);
    }

    public static void generateMines(int row, int col, int num, HashSet<Integer> safeCells){
        //生成随机地雷位置的核心所在，利用了set的高效（时间复杂度均为O(1)）去重的特性。
        Random random=new Random();
        while(mineMap.size()<num){
            Integer random1=random.nextInt(row*col);
            if(!safeCells.contains(random1)){
                mineMap.add(random1);
            }
        }
    }

    public static HashSet<Integer> getMineMap() {   //供Cell和GameBoardPanel等类或方法读取
        return mineMap;
    }

    public static void clearMap(){
        mineMap.clear();
    }
}
